package com.cyx.gametool.controller;

import com.cyx.gametool.mgr.ControllerMgr;
import javafx.beans.property.ReadOnlyBooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.Control;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public abstract class AbsBaseController {
    /**
     * 错误控件集合
     */
    private final Set<Control> errorControls = new HashSet<>();

    public AbsBaseController() {
        ControllerMgr.getInstance().addController(this);
    }

    /**
     * 添加错误控件
     */
    protected final void addErrorControl(Control... controls) {
        Collections.addAll(errorControls, controls);
    }

    /**
     * 是否还有错误的控件
     */
    protected final boolean isErrorControls() {
        return !errorControls.isEmpty();
    }

    /**
     * 获取错误控件集合
     */
    protected final Set<Control> getErrorControls() {
        return errorControls;
    }

    /**
     * 控件失去焦点监听
     */
    protected final void addLostFocusListener(Control... controls) {
        for (Control control : controls) {
            control.focusedProperty().addListener(this::lostFocusListener);
        }
    }

    /**
     * 控件失去焦点监听
     *
     * @param observable
     * @param oldValue
     * @param newValue
     */
    private void lostFocusListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
        if (!newValue) {
            Control control = (Control) ((ReadOnlyBooleanProperty) observable).getBean();
            System.out.println("控件失去焦点: " + control.getId());
            lostFocus(control);
        }
    }

    /**
     * 控件失去焦点事件
     *
     * @param control 控件
     */
    protected void lostFocus(Control control) {
    }


}
